package org.easyspring.util;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @description:
 * @author：hy
 * @date: 2025/4/30
 */
public class JsonToJavaExample {
    public static void main(String[] args) throws Exception {
//  String contentVoStr = "{\"contentType\":1}";
//  String reqStr="{\"address\":\"中国香港·中国\",\"browseFlag\":1,\"cityId\":1003254,\"content\":\"<p>无可无不可无可无不可&nbsp;</p>\",\"contentPoiRelationList\":[],\"contentType\":2,\"countryId\":1000001,\"deleteRelations\":[],\"homeImg\":\"\",\"hotelRelationFlag\":0,\"mediaType\":1,\"provinceId\":1003253,\"sourceType\":3,\"title\":\"56香港中国\",\"topicIds\":[],\"updated\":false,\"userDiyHomeFlag\":0} \n";
//  ObjectMapper mapper = new ObjectMapper();
//        ContentSaveReq contentSaveReq = mapper.readValue(reqStr, ContentSaveReq.class);
//        ContentVo contentVo = mapper.readValue(contentVoStr, ContentVo.class);
//        // 输出结果验证
//        System.out.println("contentVo: " + contentVo);
//        System.out.println("ContentSaveReq: " + contentSaveReq);
//        updPoiRelation(contentVo,contentSaveReq.getContentPoiRelationList(),transPoiRelationReqToVos(contentSaveReq.getContentPoiRelationList()),contentSaveReq);
//        String jsonArray = "[{\"createTime\":1655024923000,\"id\":8385,\"modifyTime\":1655024923000,\"name\":\"综合商场\",\"status\":1,\"tagMainId\":25},{\"createTime\":1655024930000,\"id\":8393,\"modifyTime\":1655024930000,\"name\":\"数码电器\",\"status\":1,\"tagMainId\":25},{\"createTime\":1655024930000,\"id\":8396,\"modifyTime\":1655024930000,\"name\":\"食品\",\"status\":1,\"tagMainId\":25},{\"createTime\":1655024930000,\"id\":8398,\"modifyTime\":1655024930000,\"name\":\"母婴儿童\",\"status\":1,\"tagMainId\":25},{\"createTime\":1655024931000,\"id\":8399,\"modifyTime\":1655024931000,\"name\":\"超市/便利店\",\"status\":1,\"tagMainId\":25},{\"createTime\":1655024931000,\"id\":8400,\"modifyTime\":1655024931000,\"name\":\"药妆店/药店\",\"status\":1,\"tagMainId\":25},{\"createTime\":1655024931000,\"id\":8401,\"modifyTime\":1655024931000,\"name\":\"奢侈品\",\"status\":1,\"tagMainId\":25},{\"createTime\":1655024931000,\"id\":8402,\"modifyTime\":1655024931000,\"name\":\"品牌/精品店\",\"status\":1,\"tagMainId\":25}] \n";
//        ObjectMapper objectMapper = new ObjectMapper();
//
//        // 将 JSON 字符串转换为 List<TagSubVo>
//        List<TagSubVo> tagSubVos = objectMapper.readValue(jsonArray, new TypeReference<List<TagSubVo>>() {});
//        SearchPoiConditionResp resp = new SearchPoiConditionResp();
//        fillSearchData(tagSubVos,resp,TagSubVo.class);
//        System.out.println(resp);
        String s = formatDataGroups(Arrays.asList("1", "2", "3"), Arrays.asList("2", "3", "4"));
        System.out.println(s);
        String s1 = formatDataGroups(Arrays.asList("1", "2", "3"), null);
        System.out.println(s1);
        String s2 = formatDataGroups(null, Arrays.asList("2", "3", "4"));
        System.out.println(s2);
    }

    /**
     * 将不同组的数据拼接成 key:value 的形式。
     * 支持只有部分类型的数据存在的情况。
     *
     * @param cList 类型为 'c' 的数据列表
     * @param pList 类型为 'p' 的数据列表
     * @return 拼接后的字符串，如 "c:1,2,3p:2,3,4" 或者仅 "c:1,2,3" 或者仅 "p:2,3,4"
     */
    public static String formatDataGroups(List<String> cList, List<String> pList) {
        StringBuilder sb = new StringBuilder();

        // 如果 cList 不为空，则添加到结果中
        if (cList != null && !cList.isEmpty()) {
            appendGroup(sb, "c", cList);
        }

        // 如果 pList 不为空，则添加到结果中
        if (pList != null && !pList.isEmpty()) {
            // 确保在添加 'p' 组之前没有多余的前缀字符
            if (sb.length() > 0) {
                sb.append("p");
            } else {
                sb.append("p:");
            }
            appendGroup(sb, "", pList); // 注意这里的第二个参数是空字符串，因为我们已经在前面加上了 'p'
        }

        return sb.toString();
    }

    private static void appendGroup(StringBuilder sb, String prefix, List<String> dataList) {
        // 对数据进行去重和排序
        Set<String> uniqueSet = new TreeSet<>(dataList);
        if (sb.length() > 0) {
            sb.append(prefix); // 添加前缀（例如 'c:' 或 'p:'）
        } else {
            sb.append(prefix).append(":");
        }
        boolean first = true;
        for (String item : uniqueSet) {
            if (!first) {
                sb.append(",");
            }
            sb.append(item);
            first = false;
        }
    }
    public static void fillSearchData(List objectList, SearchPoiConditionResp resp, Class clazz) {
        if (objectList == null || objectList.isEmpty()) {
            return;
        }
        LinkedList<Normal1Resp> normal1Resps = new LinkedList<>();
        try {
            Field idFiled = clazz.getDeclaredField("id");
            Field midIdFiled = clazz.getDeclaredField("midSubId");
            idFiled.setAccessible(true);
            midIdFiled.setAccessible(true);
            Field nameFiled = clazz.getDeclaredField("name");
            nameFiled.setAccessible(true);
            for (Object object : objectList) {
                Normal1Resp normalResp = new Normal1Resp();
                String s = null != midIdFiled && null != midIdFiled.get(object) ? midIdFiled.get(object).toString()
                        : (null != idFiled.get(object) ? idFiled.get(object).toString() : null);
                normalResp.setId(s);
                normalResp.setTitle(null !=nameFiled.get(object) ? nameFiled.get(object).toString() : null);
                normal1Resps.add(normalResp);
            }
        } catch (Exception e) {
            return;
        }
        switch (clazz.getSimpleName()) {
            case "TagMainVo":
            case "TagSubVo":
                Normal1Resp normalResp = new Normal1Resp();
                normalResp.setId("0");
                normalResp.setTitle("全部类别");
                normal1Resps.addFirst(normalResp);
                resp.setTags(normal1Resps);
                break;
            case "LocationVO":
                resp.setLocations(normal1Resps);
                break;
            default:
                break;
        }

    }

    public static void updPoiRelation(ContentVo contentVo, List<ContentPoiRelationReq> contentPoiRelationList, List<ContentPoiRelationVo> poiRelationVos, ContentSaveReq req) {
        List<Integer> regionIds = new ArrayList<>();
        if(null !=req.getCountryId()){regionIds.add(req.getCountryId());contentVo.setCountryId(req.getCountryId());}
        if(null !=req.getProvinceId()){regionIds.add(req.getProvinceId());contentVo.setProvinceId(req.getProvinceId());}
        if(null !=req.getCityId()){regionIds.add(req.getCityId());contentVo.setCityId(req.getCityId());}
        contentVo.setAddress(req.getAddress());
        Map<Long,List<ContentPoiRelationVo>> poiRelationVoMap=new HashMap<>();
        ContentPoiRelationVo vo1=new ContentPoiRelationVo();
        vo1.setTargetType(1);
        poiRelationVos.add(vo1);
        poiRelationVoMap.put(1L,poiRelationVos);
        if(CollectionUtils.isNotEmpty(contentPoiRelationList)){poiRelationVoMap.put(contentVo.getContentId(),poiRelationVos);}
        String pointCityData = PointCityDataUtils.transPointCityData(contentVo, queryRegions(regionIds), poiRelationVoMap);
        System.out.println(pointCityData);

    }
    public static List<ContentPoiRelationVo> transPoiRelationReqToVos(List<ContentPoiRelationReq> contentPoiRelationList) {
        List<ContentPoiRelationVo> poiRelationVos=new ArrayList<>();
        if(CollectionUtils.isNotEmpty(contentPoiRelationList)){
            contentPoiRelationList.stream().filter(p->p.getTargetType().equals(2)).forEach(p->{
                ContentPoiRelationVo poiRelationVo = new ContentPoiRelationVo();
                poiRelationVo.setId(p.getId());
                poiRelationVo.setContentId(null !=p.getContentId() ? p.getContentId().longValue() : null);
                poiRelationVo.setAuditPoiId(p.getAuditPoiId());
                poiRelationVo.setImageId(p.getImageId());
                poiRelationVo.setStatus(p.getStatus());
                poiRelationVo.setTargetId(p.getTargetId());
                poiRelationVo.setTargetName(p.getTargetName());
                poiRelationVo.setTargetType(p.getTargetType());
                poiRelationVos.add(poiRelationVo);
            });
        }
        return poiRelationVos;
    }

    public static List<RelationData> queryRegions(List<Integer> regionIds){
        if(CollectionUtils.isEmpty(regionIds)){return Collections.emptyList();}
        List<RelationData> relationRegions = new ArrayList<>();
        RelationData r1 = new RelationData();
        r1.setTargetType(3);
        r1.setTargetId(1000001);
        r1.setTargetName("中国");
        relationRegions.add(r1);
        RelationData r2 = new RelationData();
        r2.setTargetType(3);
        r2.setTargetId(1003253);
        r2.setTargetName("中国香港");
        relationRegions.add(r2);
        RelationData r3 = new RelationData();
        r3.setTargetType(3);
        r3.setTargetId(1003254);
        r3.setTargetName("中国香港");
        relationRegions.add(r3);
        RelationData r4 = new RelationData();
        r4.setTargetType(3);
        r4.setTargetId(1003274);
        r4.setTargetName("中国澳门");
        relationRegions.add(r4);
        return relationRegions;
    }


}
